package com.lwl.java.base;

import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.Random;

public class CyclicBarrierDemo {

    private static final int THREAD_COUNT = 3;
    private static final int PHASE_COUNT = 2;

    public static void main(String[] args) {
        // 创建CyclicBarrier，指定线程数和到达屏障点后执行的动作
        CyclicBarrier barrier = new CyclicBarrier(THREAD_COUNT, () -> {
            System.out.println("--- 所有线程均已完成本阶段任务，准备进入下一阶段 ---");
        });

        ExecutorService executor = Executors.newFixedThreadPool(THREAD_COUNT);
        Random random = new Random();

        for (int i = 0; i < THREAD_COUNT; i++) {
            final int threadId = i;
            executor.execute(() -> {
                try {
                    for (int phase = 1; phase <= PHASE_COUNT; phase++) {
                        // 模拟每个阶段的工作
                        int workTime = random.nextInt(500) + 500;
                        Thread.sleep(workTime);
                        System.out.println("线程 " + threadId + " 完成阶段 " + phase + " 的工作");

                        // 等待其他线程都到达这个阶段的屏障点
                        barrier.await();
                    }
                    System.out.println("线程 " + threadId + " 所有阶段任务全部完成！");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }
        executor.shutdown();
    }
}